package net.godbirds.aps;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.godbirds.boot.utils.MD5Util;
import net.godbirds.domain.mapper.TDefUserMapper;
import net.godbirds.domain.model.TDefUser;
import net.godbirds.domain.model.TDefUserExample;
@Service
public class WelcomeService {

	@Autowired
	TDefUserMapper tDefUserMapper;
	Logger logger = Logger.getLogger(WelcomeService.class);
	public Map<String,Object> login(TDefUser tUser){
		Map<String,Object> rtv = new HashMap<String,Object>();
		if(tUser == null || tUser.getUserCode() == null) {
			rtv.put("msg", "请录入用户名");
			return rtv;
		}
		if(tUser == null || tUser.getUserPass() == null) {
			rtv.put("msg", "请录入密码");
			return rtv;
		}
		TDefUserExample example = new TDefUserExample();
		example.createCriteria().andUserCodeEqualTo(tUser.getUserCode());
		List<TDefUser> l = tDefUserMapper.selectByExample(example);
		if(l == null || l.size() <= 0) {
			logger.info("用户："+tUser.getUserCode()+"不存在");
			rtv.put("msg", "用户名或密码错误");
			return rtv;
		}
		try {
			String ePass = MD5Util.encrypt(tUser.getUserPass());
			if(ePass.equals(l.get(0).getUserPass())) {
				rtv.put("tUser", l.get(0));
				return rtv;
			}
			logger.info("用户："+tUser.getUserCode()+"密码错误");
			rtv.put("msg", "用户名或密码错误");
			return rtv;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			rtv.put("msg", "登录异常，请重试！");
		}
		return rtv;
	}
	public Map<String, Object> attach(TDefUser tUser){
		Map<String,Object> rtv = new HashMap<String,Object>();
		if(tUser == null || tUser.getUserCode() == null) {
			rtv.put("msg", "请录入用户名");
			return rtv;
		}
		if(tUser == null || tUser.getUserPass() == null) {
			rtv.put("msg", "请录入密码");
			return rtv;
		}
		try {
			//1、判断用户是否存在
			TDefUserExample example = new TDefUserExample();
			example.createCriteria().andUserCodeEqualTo(tUser.getUserCode());
			List<TDefUser> l = tDefUserMapper.selectByExample(example);
			if(l!= null && l.size() > 0) {
				rtv.put("msg", "用户已存在，请重试新注册！");
				rtv.put("error", "1");
				return rtv;
			}
			//2、不存在注册
			String oPass = tUser.getUserPass();
			String ePass = MD5Util.encrypt(oPass);
			tUser.setUserPass(ePass);
			tUser.setInsertTime(new Date());
			tUser.setLastModifyTime(new Date());
			tUser.setOperator(tUser.getUserCode());
			tUser.setLastModifyer(tUser.getUserCode());
			tUser.setStatus("1");
			tUser.setLockState("0");
			int i = tDefUserMapper.insert(tUser);
			if(i > 0) {
				rtv.put("msg", "注册成功");
				rtv.put("userPass", oPass);
				rtv.put("userCode", tUser.getUserCode());
			}
			return rtv;
		} catch (Exception e) {
			e.printStackTrace();
			rtv.put("msg", "注册异常，请重试！");
		}
		return rtv;
	}
}
